<template>
  <div class="container">
    <Breadcrumb
      :items="['menu.user-management', 'menu.user-management.searchTable']"
    />
    <!--  对于用户历史 逻辑还是和群组一个逻辑，控制谁在显示 -->
    <a-card
      v-if="mainVisible == true"
      class="general-card"
      :title="$t('menu.user-management.searchTable')"
    >
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="formModel"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
            label-align="left"
          >
            <!--这是上面的
                  用这个进行模糊查询
            -->
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="number" label="用户名称">
                  <a-input
                    v-model="formModel.username"
                    placeholder="请输入用户名称……"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <!--变得窄一点-->

        <a-divider style="height: 42px" direction="vertical" />
        <a-col :flex="'192px'" style="text-align: right">
          <a-space direction="horizontal" :size="18">
            <a-button type="primary" @click="search">
              <template #icon>
                <icon-search />
              </template>
              {{ $t('searchTable.form.search') }}
            </a-button>
            <a-button @click="reset">
              <template #icon>
                <icon-refresh />
              </template>
              {{ $t('searchTable.form.reset') }}
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 0" />
      <a-row style="margin-bottom: 16px">
        <a-col :span="16">
          <a-space>
            <a-button type="primary" @click="handleCreate">
              <!--这个是新增-->
              <template #icon>
                <icon-plus />
              </template>
              {{ $t('searchTable.operation.create') }}
            </a-button>
            <!-- 这是个批量导入的按钮 -->
            <a-upload action="http://localhost:8080/user/user/import/user">
              <template #upload-button>
                <a-button> 批量导入 </a-button>
              </template>
            </a-upload>
          </a-space>
        </a-col>
        <a-col :span="8" style="text-align: right">
          <a-button @click="downloadButton">
            <template #icon>
              <icon-download />
            </template>
            {{ $t('searchTable.operation.download') }}
          </a-button>
        </a-col>
      </a-row>

      <!--到了下面展示的了-->

      <a-table
        row-key="id"
        :loading="loading"
        :pagination="pagination"
        :data="renderData"
        :bordered="false"
        @page-change="onPageChange"
      >
        <template #columns>
          <a-table-column title="用户名称" data-index="username" />
          <a-table-column title="用户密码" data-index="password" />
          <a-table-column
            title="用户昵称"
            data-index="nickname"
          ></a-table-column>
          <a-table-column title="手机号" data-index="mobile"> </a-table-column>
          <a-table-column title="邮箱" data-index="email" />
          <a-table-column title="创建时间" data-index="createDate" />
          <a-table-column title="操作" data-index="operations">
            <!-- 后面的修改和删除 -->

            <template #cell="record">
              <a-button
                type="text"
                status="warning"
                size="small"
                @click="handleModify(record)"
              >
                <!-- {{ $t('searchTable.columns.operations.view') }} -->
                修改
              </a-button>
              <a-button
                type="text"
                status="danger"
                size="small"
                @click="deleteZuhu(record)"
              >
                <!-- {{ $t('searchTable.columns.operations.view') }} -->
                删除
              </a-button>
              <a-button
                type="text"
                status="error"
                size="small"
                @click="history(record)"
              >
                <!-- {{ $t('searchTable.columns.operations.view') }} -->
                历史
              </a-button>
            </template>
          </a-table-column>
        </template>
      </a-table>

      <!--新增的弹窗-->
      <!-- 新建-->
      <createUser v-model:visible="createVisible"></createUser>
      <!-- 修改-->
      <!--        @fetchData = "fetchData"
-->
      <modifyUser
        v-if="modifyVisible"
        v-model:visible="modifyVisible"
        :dialog-table-value="dialogTableValue"
      ></modifyUser>
    </a-card>

    <!-- 查看用户历史的部分 -->
    <a-card v-if="mainVisible == false" title="用户历史">
      <!--  返回的按钮  -->
      <a-button @click="backButton"> 返回 </a-button>
      <!-- 真正展示数据 -->
      <a-table
        row-key="id"
        :loading="loading"
        :pagination="pagination1"
        :data="historyCon"
        :bordered="false"
        @page-change="onPageChange1"
      >
        <template #columns>
          <a-table-column title="密码" data-index="password" />
          <a-table-column title="昵称" data-index="nickname" />
          <a-table-column title="邮箱" data-index="email" />
          <a-table-column title="手机号" data-index="mobile" />
          <a-table-column
            :title="$t('searchTable.columns.operations')"
            data-index="operations"
          >
            <!-- 获取一行的信息 -->
            <template #cell="record">
              <a-button
                type="text"
                status="warning"
                size="small"
                @click="deleteHistory(record)"
              >
                删除
              </a-button>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <a-modal v-model:visible="visible" @ok="handleOk" @cancel="handleCancel">
      <template #title> 下载确认框 </template>
      <div>点击确定即可下载所有用户具体信息！</div>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { computed, ref, reactive } from 'vue';
  import { useI18n } from 'vue-i18n';
  import useLoading from '@/hooks/loading';
  import { queryPolicyList, PolicyRecord, PolicyParams } from '@/api/list';
  import { Pagination } from '@/types/global';
  import type { SelectOptionData } from '@arco-design/web-vue/es/select/interface';
  import { useIdFindHistory, useIdDeleteHistory, deleteUser } from '@/api/user';
  import { Message } from '@arco-design/web-vue';
  import createUser from './createUser.vue';
  import modifyUser from './modifyUser.vue';

  const generateFormModel = () => {
    return {
      username: '',
      name: '',
      contentType: '',
      filterType: '',
      createdTime: [],
      status: '',
    };
  };
  const { loading, setLoading } = useLoading(true);
  const { t } = useI18n();
  const renderData = ref<PolicyRecord[]>([]);
  const formModel = ref(generateFormModel());
  const basePagination: Pagination = {
    page: 1,
    limit: 20,
  };
  const basePagination1: Pagination = {
    page: 1,
    limit: 20,
  };
  const pagination = reactive({
    ...basePagination,
  });
  const pagination1 = reactive({
    ...basePagination1,
  });
  const role = '2';

  const fetchData = async (
    params: PolicyParams = {
      page: 1,
      limit: 20,
      role: 2,
      username: formModel.value.username,
      isDeleted: '0',
    }
  ) => {
    setLoading(true);
    try {
      const { data } = await queryPolicyList(params);
      console.log('这里是fetchdata');

      renderData.value = data.list;
      pagination.page = params.page;
      pagination.total = data.total;
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };

  // 主页面是否可见
  const mainVisible = ref(true);

  // 针对历史的变量
  const historyCon = ref({});

  // 下面是用户历史
  const history = async (record: any) => {
    mainVisible.value = false;

    // 然后要发请求了
    const toBack = {
      page: 0,
      answerLimit: 10,
      userId: record.record.id,
    };
    const { data } = await useIdFindHistory(toBack);
    console.log('查询用户历史');
    console.log(data);
    // 这才是需要的 赋值
    console.log(data.list);
    historyCon.value = data.list;
  };

  // 返回的按钮
  const backButton = () => {
    mainVisible.value = true;
  };

  // 删除历史
  const deleteHistory = async (record: any) => {
    console.log(record.record.id);
    await useIdDeleteHistory([record.record.id]);
    Message.success('删除成功');
    // 再发一次查询历史的接口
    const toBack = {
      page: 0,
      answerLimit: 10,
      userId: record.record.userId,
    };
    const { data } = await useIdFindHistory(toBack);
    historyCon.value = data.list;
  };

  // 新增按钮的一系列
  // 控制出来的那个东西
  const modifyVisible = ref(false);
  const createVisible = ref(false);
  // 修改用户的
  const dialogTableValue = ref({});

  const handleCreate = () => {
    createVisible.value = true;
  };

  // 修改用户的方法
  const handleModify = (data: any) => {
    modifyVisible.value = true;
    console.log(data.record);
    dialogTableValue.value = JSON.parse(JSON.stringify(data.record));
  };

  const search = () => {
    fetchData({
      ...basePagination,
      ...formModel.value,
      role,
    } as unknown as PolicyParams);
  };
  const onPageChange = (page: number) => {
    fetchData({ ...basePagination, page });
  };
  const onPageChange1 = (page: number) => {
    fetchData({ ...basePagination1, page });
  };

  fetchData();
  const reset = () => {
    formModel.value = generateFormModel();
  };

  // 在查询页面删除
  const deleteZuhu = async (record: any) => {
    await deleteUser([record.record.id]);
    Message.success('删除成功');
    fetchData();
  };

  const visible = ref(false);

  // 这是下载的按钮的
  // 点击下载后的方法
  const downloadButton = () => {
    visible.value = true;
  };

  // const handleClick = () => {
  //   visible.value = true;
  // };
  const handleOk = () => {
    visible.value = false;
    Message.success('下载成功!');
  };
  const handleCancel = () => {
    visible.value = false;
  };
</script>

<script lang="ts">
  export default {
    name: 'UserSearchTable',
  };
</script>

<style scoped lang="less">
  .container {
    padding: 0 20px 20px 20px;
  }

  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }
</style>
